<template>
  <div class="coupon-issue">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="优惠券名称">
          <el-input v-model="searchForm.name" placeholder="请输入优惠券名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 列表区域 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>待发放优惠券列表</span>
        </div>
      </template>

      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="优惠券ID" width="200"></el-table-column>
        <el-table-column prop="name" label="优惠券名称"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button 
              size="small" 
              type="primary" 
              @click="handleIssue(scope.row)"
              :disabled="scope.row.status !== 1"
            >
              发放
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination">
        <el-pagination 
          v-model:current-page="pagination.pageNo" 
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" 
          :total="pagination.total" 
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" 
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 发放优惠券弹窗 -->
    <el-dialog v-model="issueDialogVisible" title="发放优惠券" width="600px" @close="handleDialogClose">
      <el-form 
        :model="issueForm" 
        :rules="issueRules" 
        ref="issueFormRef" 
        label-width="120px"
      >
        <el-form-item label="优惠券名称">
          <el-input v-model="couponName" disabled></el-input>
        </el-form-item>

        <el-form-item label="发放开始时间" prop="issueBeginTime">
          <el-date-picker
            v-model="issueForm.issueBeginTime"
            type="datetime"
            placeholder="选择发放开始时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="发放结束时间" prop="issueEndTime">
          <el-date-picker
            v-model="issueForm.issueEndTime"
            type="datetime"
            placeholder="选择发放结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="有效期设置">
          <el-radio-group v-model="validityType" @change="handleValidityTypeChange">
            <el-radio :label="1">固定天数</el-radio>
            <el-radio :label="2">指定时间范围</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="有效天数" prop="termDays" v-if="validityType === 1">
          <el-input-number v-model="issueForm.termDays" :min="1" :max="365"></el-input-number>
          <span style="margin-left: 10px">天</span>
        </el-form-item>

        <template v-if="validityType === 2">
          <el-form-item label="有效开始时间" prop="termBeginTime">
            <el-date-picker
              v-model="issueForm.termBeginTime"
              type="datetime"
              placeholder="选择有效开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="有效结束时间" prop="termEndTime">
            <el-date-picker
              v-model="issueForm.termEndTime"
              type="datetime"
              placeholder="选择有效结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </template>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="issueDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitIssueForm" :loading="issueLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import couponApi from '@/api/coupon'
import { type CouponListResponseType, type CouponQueryType, type CouponIssueType } from '@/api/coupon'
import dayjs from 'dayjs'

// 搜索表单
const searchForm = ref({
  name: ''
})

// 分页参数
const pagination = ref({
  pageNo: 1,
  pageSize: 10,
  total: 0
})

// 表格数据
const tableData = ref<CouponListResponseType[]>([])
const loading = ref(false)

// 发放弹窗相关
const issueDialogVisible = ref(false)
const issueFormRef = ref()
const issueLoading = ref(false)
const currentIssueId = ref('')

// 优惠券名称（只读）
const couponName = ref('')

// 有效期设置类型：1-固定天数，2-指定时间范围
const validityType = ref(1)

// 发放表单数据
const issueForm = ref<CouponIssueType>({
  id: '',
  issueBeginTime: '',
  issueEndTime: '',
  termDays: 7,
  termBeginTime: '',
  termEndTime: ''
})

// 发放表单验证规则
const issueRules = {
  issueBeginTime: [
    { required: true, message: '请选择发放开始时间', trigger: 'change' }
  ],
  issueEndTime: [
    { required: true, message: '请选择发放结束时间', trigger: 'change' }
  ],
  termDays: [
    { required: true, message: '请输入有效天数', trigger: 'blur' }
  ],
  termBeginTime: [
    { required: true, message: '请选择有效开始时间', trigger: 'change' }
  ],
  termEndTime: [
    { required: true, message: '请选择有效结束时间', trigger: 'change' }
  ]
}

// 获取优惠券列表
const getCouponList = async () => {
  loading.value = true
  const couponQuery: CouponQueryType = {
    pageNo: pagination.value.pageNo,
    pageSize: pagination.value.pageSize,
    sortBy: 'id',
    isAsc: false,
    discountType: 0,
    status: 1, // 只获取待发放的优惠券
    name: searchForm.value.name
  }
  try {
    const res: any = await couponApi.queryCouponByPage(couponQuery)
    tableData.value = res.data.data.list
    pagination.value.total = res.data.data.total
  } catch (error) {
    ElMessage.error('获取优惠券列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索优惠券
const handleSearch = () => {
  pagination.value.pageNo = 1
  getCouponList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: ''
  }
  pagination.value.pageNo = 1
  getCouponList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.value.pageSize = val
  pagination.value.pageNo = 1
  getCouponList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.value.pageNo = val
  getCouponList()
}

// 发放优惠券
const handleIssue = (row: CouponListResponseType) => {
  // 重置表单
  issueForm.value = {
    id: row.id,
    issueBeginTime: '',
    issueEndTime: '',
    termDays: 7,
    termBeginTime: '',
    termEndTime: ''
  }
  
  currentIssueId.value = row.id
  couponName.value = row.name
  validityType.value = 1 // 默认选择固定天数
  issueDialogVisible.value = true
}

// 有效期类型改变
const handleValidityTypeChange = () => {
  // 清空另一组字段
  if (validityType.value === 1) {
    issueForm.value.termBeginTime = ''
    issueForm.value.termEndTime = ''
  } else {
    issueForm.value.termDays = 0
  }
}

// 关闭弹窗时的处理
const handleDialogClose = () => {
  if (issueFormRef.value) {
    issueFormRef.value.resetFields()
  }
}

// 提交发放表单
const submitIssueForm = async () => {
  if (!issueFormRef.value) return
  
  await issueFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      issueLoading.value = true
      try {
        // 构造提交数据
        const formData: any = {
          id: currentIssueId.value,
          issueBeginTime: issueForm.value.issueBeginTime,
          issueEndTime: issueForm.value.issueEndTime
        }
        
        if (validityType.value === 1) {
          formData.termDays = issueForm.value.termDays
        } else {
          formData.termBeginTime = issueForm.value.termBeginTime
          formData.termEndTime = issueForm.value.termEndTime
        }
        
        const res: any = await couponApi.issueCoupon(formData)
        
        if (res.data.code === 200) {
          ElMessage.success('发放优惠券成功')
          issueDialogVisible.value = false
          getCouponList()
        } else {
          ElMessage.error(`发放优惠券失败: ${res.data.msg}`)
        }
      } catch (error) {
        ElMessage.error('发放优惠券失败')
      } finally {
        issueLoading.value = false
      }
    }
  })
}

// 初始化加载数据
onMounted(() => {
  getCouponList()
})

// 辅助函数
const formatDate = (date: Date) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

const getStatusName = (status: number) => {
  switch (status) {
    case 1: return '待发放'
    case 2: return '未开始'
    case 3: return '进行中'
    case 4: return '已结束'
    case 5: return '暂停'
    default: return ''
  }
}

const getStatusType = (status: number) => {
  switch (status) {
    case 1: return 'info'
    case 2: return 'primary'
    case 3: return 'success'
    case 4: return 'warning'
    case 5: return 'danger'
    default: return ''
  }
}
</script>

<style scoped>
.coupon-issue {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  text-align: right;
}
</style>